import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import { Toast,Dialog } 	from 'vant';
Vue.use(Toast,Dialog);

export default {
	name: 'buyType',
	data(){
		return {
			name:'',			//购买的币种名称
			account:0,			//购买币种数量
			amountOfMoney:0,	//购买金额
			userName:'',		//当前实名认证用户名
			OTCWorkTime:'',		//OTC服务时间
			list:[],
			loading:false,		//按钮是否加载中
			token:'',
			EOSAccount:'',
			ETHAccount:'',
			error:false
		}
	},
	computed:{
		isIphoneX(){
			return util.isIphoneX()
		},
		isIphone(){
			return util.client()
		},
		isMYKEY(){
			return util.isMYKEY()
		}
	},
	methods:{
		next(orderId,state){
			//下一步
			// this.$router.replace({
			// 	path:'/orderDetail',
			// 	query:{
			// 		id:orderId,
			// 		pageState:1,
			// 		death:1
			// 	}
			// })
			let query = {
				death:1,
			}
			if(state == 2 || state == 4){
				query.id = orderId;
				query.pageState = 1
			}else{
				query.orderId = orderId
			}
			if(state == 4){
				//判断记录从下单页过去
				sessionStorage.setItem('makeOrderDown',1)
			}
			this.$router.replace({
				path:(state==2 || state==4)?'/orderDetail':'/makeOrder',
				query:query
			})
		},
		showDialog(orderId,state){
			//历史交易未结束提示
			Dialog.confirm({
				title: '您有一笔购买订单未完成',
				message: '请先完成此订单交易',
				className:'fullDialog2',
				cancelButtonColor:'#1989fa',
				confirmButtonText:'进入订单',
				cancelButtonText:'取消',
				overlayClass:'sellType-mark'
			}).then(() => {
				this.next(orderId,state);
				console.log('confirm')
			}).catch(() => {
				console.log('cancel')
				this.loading = false;
			})
		},
		renderLocal(){
			//渲染可能的缓存数据
			let otcPayConfig = util.getStorage('otcPayConfig');
			let verifiedInfo = util.getStorage('verifiedInfo');
			if(otcPayConfig && verifiedInfo){
				otcPayConfig = JSON.parse(otcPayConfig);
				this.OTCWorkTime = otcPayConfig.otc_serve_desc;
				this.userName = JSON.parse(verifiedInfo).name;
				util.bridgeData(otcPayConfig.pay).then(list => {
					//若没有推荐，则默认第一个
					if(list.filter(item => item.isSelected).length === 0) list[0].isSelected = true;
					this.list = list;
				}).catch(error => {
					Toast('数据错误')
				})
			}
		},
		init(){
			//获取付款方式以及服务时间
			let params = {};
			if(this.isMYKEY) params.token = this.token || util.getToken();
			util.fetch(util.ajaxUrl()+'/mykey/otc-pay-config',params).then(res => {
				if(res.retCode === 0){
					this.OTCWorkTime = res.retData.otc_serve_desc;
					util.bridgeData(res.retData.pay).then(list => {
						//若没有推荐，则默认第一个
						if(list.filter(item => item.isSelected).length === 0) list[0].isSelected = true;
						this.list = list
					}).catch(error => {
						Toast('数据错误')
					})
					util.setStorage('otcPayConfig',res.retData)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		getUserName(){
			//获取用户名
			util.fetch(util.ajaxUrl()+`/user/verified-info`,{
				token:this.token || util.getToken()
			}).then(res => {
				if(res.retCode === 0){
					this.userName = res.retData.name;
					util.setStorage('verifiedInfo',res.retData)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		getPrice(){
			//获取每个B单价
			util.getPriceByName(this.name,1,this.account).then(price => {
				this.amountOfMoney = util.accMul(price,this.account).toFixed(2)
			}).catch(() => {
				Toast('获取实时单价失败')
			})
			setTimeout(() => {
				this.getPrice();
			},util.time)
		},
		makeOrder(){
			//下单
			if(!this.loading){
				this.loading = true;
				let _arr = this.list.filter(item => item.isSelected);
				if(_arr.length === 0) _arr = this.list[0];
				let _type = _arr[0].type;
				//下单接口
				let params = {
					token:this.token || util.getToken(),
					orderusdt:this.account,					//购买币种数量
					in_type:_type==3?4:_type,				//下单类型  1:支付宝  2:银行卡  4:微信
					currency_id:this.name,					//购买币种名称
				};
				if(this.isMYKEY) {
					params.address = this.name === 'EOS'?this.EOSAccount:this.ETHAccount;
					//mykey中判断可能获取不到ETH地址问题
					if(this.name != 'EOS' && (!this.ETHAccount || this.ETHAccount==='undefined')){
						if(typeof web3 !== 'undefined'){
							this.loading = false;
							Dialog.confirm({
			                    title: '提示',
			                    message: '获取ETH地址失败，请先开通账号。若已开通，请稍后刷新重试',
			                    className:'sellType-dialog',
			                    cancelButtonColor:'#1989fa',
			                    confirmButtonText:'确定',
			                    cancelButtonText:'取消',
			                    overlayClass:'sellType-mark'
			                }).then(() => {
			                	window.location.reload();
			                	// web3.eth.create();
			                }).catch(() => {
			                    console.log('cancel')
			                })
						}else{
							Toast('请先升级app到最新版本')
						}
						return
					}
				}
				util.checkDialog().then(confirm => {
					//点击确定
					util.fetch(util.ajaxUrl()+`/mykey/otc-inmoney`,params).then(res => {
						if(res && res.retCode == 0){
							setTimeout(() => {
								if(res && res.retData && res.retData.id){
									this.next(res.retData.id)
								}else{
									this.loading = false;
								}
							},500)
						}else if(res && res.retCode == -1){
							//弹窗(先判断订单状态)
							util.fetch(util.ajaxUrl()+`/mykey/otc-inmoney-detail`,{
								token:this.token || util.getToken(),
								id:res.retData.id
							}).then(xhr => {
								if(xhr.retCode === 0){
									this.showDialog(res.retData.id,xhr.retData.state)
								}else{
									Toast(xhr.retMsg || '未知错误')
								}
								this.loading = false;
							}).catch(error => {
								console.log(error)
							})
						}else{
							this.loading = false;
							Toast(res.retMsg || '未知错误')
						}
					}).catch(error => {
						this.loading = false;
						console.log(error)
					})
				},cancel => {
					this.loading = false;
				})
			}
		},
		goChoice(_item){
			//是否选中
			this.list.map(item => {
				item.isSelected = item.type === _item.type?true:false
			})
		},
		goBack(){
			util.navigateBack(-1,this)
		}
	},
	created() {
		util.waitSDKReady().then(token => {
			this.token = token;
			this.EOSAccount = util.getStorage('EOSAccount');
			this.ETHAccount = util.getStorage('ETHAccount');
			let _query = this.$route.query;
			if(_query.name && _query.account){
				this.name = _query.name;
				this.account = _query.account;
				//检测没获取到EOSAccount或ETHAccount的情况
				if(this.isMYKEY && this.name === 'EOS' && !this.EOSAccount){
					Toast('获取EOS地址失败');
					this.error = true;
				}else if(this.isMYKEY && this.name != 'EOS' && (!this.ETHAccount || this.ETHAccount==='undefined')){
					Toast('获取ETH地址失败，请退出重试');
					this.error = true;
				}else{
					this.renderLocal();
					this.init();
					this.getUserName();
					this.getPrice();
				}
			}else{
				Toast('数据格式错误')
			}
		}).catch((e) => {
			Toast('获取token失败')
		})
		setTimeout(() => {
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
		},500)
    }
}